﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using AdministrationWeb;

namespace AdministrationWeb.Administration
{
    public partial class MentorsViewedReport : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (tbxEnd.Text == "")
            {
                tbxEnd.Text = DateTime.Now.ToString("MM/dd/yyyy");
            }
        }

        protected void btnRun_Click(object sender, EventArgs e)
        {

            if (Page.IsValid)
            {
                /*get value to search by
                 * 1 = mentor
                 * 2 = pathway
                 * 3 = focus
                 * */
                MentorReport mr = new MentorReport();
                int ddlValue = Convert.ToInt32(ddlGroupby.SelectedValue);
                DateTime endDate = Convert.ToDateTime(tbxEnd.Text);
                var endOfDay = new TimeSpan(23, 59, 59);
                endDate = endDate.Date + endOfDay;
                DateTime startDate = Convert.ToDateTime(tbxStart.Text);
                String endDateString = String.Format("{0:yyyy-MM-dd}", endDate);
                String startDateString = String.Format("{0:yyyy-MM-dd}", startDate);
                GridViewMentors.Visible = true;
                switch (ddlValue)
                {
                    case 1:
                        SqlDataSource1.SelectParameters.Clear();
                        SqlDataSource1.SelectCommand = formatSQl(mr.getMentorViewsSql(), startDate, endDate);
                        break;
                    case 2:
                        SqlDataSource1.SelectParameters.Clear();
                        SqlDataSource1.SelectCommand = formatSQl(mr.getPathwayViewsSql(), startDate, endDate);
                        break;
                    case 3:
                        SqlDataSource1.SelectParameters.Clear();
                        SqlDataSource1.SelectCommand = formatSQl(mr.getFocusViewsSql(), startDate, endDate);
                        break;
                    default:
                        SqlDataSource1.SelectParameters.Clear();
                        SqlDataSource1.SelectCommand ="SELECT * FROM mentor LIMIT 0";
                        break;
                }
            }
        }

        private string formatSQl(string sql, DateTime startDate, DateTime endDate)
        {
            //format dates
            string startDateString = "\"" + String.Format("{0:yyyy-MM-dd HH:mm:ss}", startDate) + "\"";
            string endDateString = "\"" + String.Format("{0:yyyy-MM-dd HH:mm:ss}", endDate) + "\"";
            string temp1, temp2;
            temp1 = sql.Replace("@minDate", startDateString);
            temp2 = temp1.Replace("@maxDate", endDateString);
            return temp2;
        }

        private string escapeFields(string fieldToEscape)
        {
            if (fieldToEscape.Contains(","))
            {
                if (fieldToEscape.Contains("\""))
                {
                    return "\"" + fieldToEscape.Replace("\"", "\"\"") + "\"";
                }
                else
                {
                    return "\"" + fieldToEscape + "\"";
                }
            }
            else
            {
                return fieldToEscape;
            }
        }

        protected void btnExport_Click(object sender, EventArgs e)
        {
           

            if (Page.IsValid)
            {
                DateTime currentDate = DateTime.Now;
                String date = String.Format("{0:mm-dd-yyyy}", currentDate);

                String sFileName;

                int ddlvalue = Convert.ToInt32(ddlGroupby.SelectedValue);
                if (ddlvalue == 1) sFileName = "mentorReport"+date+".csv";
                else if (ddlvalue == 2) sFileName = "pathwayReport" + date + ".csv";
                else if (ddlvalue == 3) sFileName = "Focusreport" + date + ".csv";
                else sFileName = "report.csv";

                //clear response
                HttpContext.Current.Response.Clear();

                //add http header for the content type to tell browser to associate file with excel
                HttpContext.Current.Response.AddHeader("content-disposition", string.Format("attachment; filename={0}", sFileName));

                HttpContext.Current.Response.ContentType = "application/ms-excel";

                System.Text.StringBuilder sbCsvValues = new System.Text.StringBuilder();

                //this will need to change based on selection
                for (int i = 0; i < GridViewMentors.HeaderRow.Cells.Count; i++)
                {
                    sbCsvValues.Append(escapeFields(GridViewMentors.HeaderRow.Cells[i].Text));
                }
                sbCsvValues.Append("\n");

                for (int j = 0; j < GridViewMentors.Rows.Count; j++)
                {
                    for (int k = 0; k < GridViewMentors.Rows[j].Cells.Count; k++)
                    {
                        //separating gridview columns with comma
                        sbCsvValues.Append(escapeFields(GridViewMentors.Rows[j].Cells[k].Text));
                        sbCsvValues.Append(",");
                    }
                    //appending new line for gridview rows
                    sbCsvValues.Append("\n");
                }

                // write the response to the HTTP stream back to the client browser.
                HttpContext.Current.Response.Write(sbCsvValues.ToString());

                // End the stream write and commit it.
                HttpContext.Current.Response.End();
            }
        }
    }
}